import { isFunction } from 'lodash-es';

import type { FormActionType } from '@/components/form';
import type { BasicCrudProps } from '@/components/crud/src/props';
import type { TableActionType } from '@/components/table';

export function useCrudButtons(
  props: BasicCrudProps,
  formInstance: Ref<FormActionType | undefined>,
  tableInstance: Ref<TableActionType | undefined>,
  openModal: () => void,
  formScene: Ref<'create' | 'modify'>,
  selectedValues: Ref<Array<string | number>>,
) {
  /**
   * 新增
   */
  function handleCreate() {
    openModal();
    nextTick().then(async () => {
      if (isFunction(props.beforeCreate)) {
        const res = await props.beforeCreate();
        formInstance.value?.setFieldsValue(toRaw(unref(res)));
      }
    });
    formScene.value = 'create';
  }

  /**
   * 编辑
   */
  function handleModify(rowData: Recordable) {
    openModal();
    nextTick().then(() => {
      formInstance.value?.setFieldsValue(rowData);
    });
    formScene.value = 'modify';
  }

  /**
   * 删除
   */
  async function handleDelete(rowData: Recordable) {
    const key = rowData[props.keyField ?? 'id'];
    if (isFunction(props.deleteRequest)) {
      await props.deleteRequest(key);
      tableInstance.value?.reload();
    }
  }

  /**
   * 批量删除
   */
  async function handleBatchDelete() {
    const keys = selectedValues.value;
    if (isFunction(props.deleteRequest)) {
      await props.deleteRequest(keys);
      tableInstance.value?.reload();
    }
  }

  return {
    handleCreate,
    handleModify,
    handleDelete,
    handleBatchDelete,
  };
}
